package org.example.gui.widget;

import org.example.dao.RecordDAO;
import org.example.entity.Record;
import org.example.gui.listener.HistoryListListener;
import org.example.gui.model.RecordTableModel;
import org.example.gui.panel.WorkingPanel;
import org.example.util.ColorUtil;
import org.example.util.GUIUtil;

import javax.swing.*;
import java.awt.*;

/**
 * HistoryTablePanel 是 HistoryPanel 中的历史记录面板
 */
public class HistoryTablePanel extends WorkingPanel {
    public static HistoryTablePanel instance = new HistoryTablePanel();
    public JButton bAdd = new JButton("新增");
    public JButton bEdit = new JButton("编辑");
    public JButton bDelete = new JButton("删除");

    private final RecordTableModel model = new RecordTableModel();
    private final JTable table = new JTable(model);


    private HistoryTablePanel() {
        GUIUtil.setColor(ColorUtil.blueColor, bAdd, bEdit, bDelete);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane sp = new JScrollPane(table);
        JPanel pSubmit = new JPanel();
        pSubmit.add(bAdd);
        pSubmit.add(bEdit);
        pSubmit.add(bDelete);

        this.setLayout(new BorderLayout());
        this.add(sp, BorderLayout.CENTER);
        this.add(pSubmit, BorderLayout.SOUTH);

        this.addListener();
    }


    public Record getSelectedRecord() {
        int index = table.getSelectedRow();
        return model.recordList.get(Math.max(index, 0));
    }


    @Override
    public void updateData() {
        model.recordList = RecordDAO.listAnyMonthByStartDay(HistoryPickerPanel.instance.date); // 更新数据模型
        table.updateUI();
    }


    @Override
    public void addListener() {
        HistoryListListener l = new HistoryListListener();
        bDelete.addActionListener(l);
        bEdit.addActionListener(l);
        bAdd.addActionListener(l);
    }
}
